<template>
  <div class="login-modal-mask">
    <div class="login-modal">
      <el-icon class="login-modal-close" @click="$emit('close')">
        <svg viewBox="0 0 1024 1024" width="24" height="24"><path d="M195.2 195.2c-12.5 12.5-12.5 32.8 0 45.3L478.7 524.8 195.2 808.3c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l283.5-283.5 283.5 283.5c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L569.3 524.8l283.5-283.5c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L524.8 478.7 241.3 195.2c-12.5-12.5-32.8-12.5-45.3 0z" fill="#909399"/></svg>
      </el-icon>
      <div class="login-title">手机号登录</div>
      <div class="login-desc">登录后可以保存你的对话记录</div>
      <el-form :model="form" :rules="rules" ref="formRef" class="login-form" @submit.prevent>
        <el-form-item prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
        <el-form-item prop="code" class="code-row">
          <el-input v-model="form.code" placeholder="输入验证码" maxlength="6" style="flex:1;" />
          <el-button style="margin-left:8px;" :disabled="codeBtnDisabled || !form.phone" @click="sendCode">{{ codeBtnText }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" class="login-btn" :loading="loading" @click="handleLogin" style="width:100%;font-size:20px;">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import Cookies from 'js-cookie'
import { useUserStore } from '@/store/user'
const userStore = useUserStore()
const form = ref({ phone: '', code: '' })
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码格式不正确', trigger: 'blur' }
  ]
}
const formRef = ref()
const codeBtnText = ref('获取验证码')
const codeBtnDisabled = ref(false)
const loading = ref(false)
let codeTimer = null

const sendCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(form.value.phone)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }
  codeBtnDisabled.value = true
  codeBtnText.value = '发送中...'
  try {
    await request.post('/api/user/sendCode', { phone: form.value.phone })
    ElMessage.success('验证码已发送')
    let seconds = 60
    codeBtnText.value = `${seconds}s后重试`
    codeTimer = setInterval(() => {
      seconds--
      codeBtnText.value = `${seconds}s后重试`
      if (seconds <= 0) {
        clearInterval(codeTimer)
        codeBtnText.value = '获取验证码'
        codeBtnDisabled.value = false
      }
    }, 1000)
  } catch (e) {
    codeBtnText.value = '获取验证码'
    codeBtnDisabled.value = false
  }
}

const handleLogin = async () => {
  await formRef.value.validate()
  loading.value = true
  try {
    // 兼容你的后端，优先用 /api/user/loginByCode
    const res = await request.post('/api/user/loginByCode', { phone: form.value.phone, code: form.value.code })
    console.log('登录返回：', res)
    if (res.code === 200 && res.data && res.data.token) {
      userStore.setToken(res.data.token)
      userStore.setUserInfo(res.data)
      // 强制写入localStorage，防止pinia失效导致token丢失
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('userInfo', JSON.stringify(res.data))
      ElMessage.success('登录成功')
      window.location.reload()
    } else {
      ElMessage.error(res.message || '登录失败')
    }
  } catch (e) {
    ElMessage.error('登录失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-modal-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.15);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-modal {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 32px rgba(0,0,0,0.12);
  padding: 40px 32px 32px 32px;
  min-width: 380px;
  max-width: 95vw;
  position: relative;
}
.login-modal-close {
  position: absolute;
  right: 16px;
  top: 16px;
  cursor: pointer;
}
.login-title {
  font-size: 28px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 8px;
}
.login-desc {
  color: #bbb;
  text-align: center;
  margin-bottom: 24px;
}
.login-form {
  margin-top: 0;
}
.code-row {
  display: flex;
  align-items: center;
}
.login-btn {
  height: 48px;
  font-size: 20px;
  border-radius: 8px;
}
</style> 